use std::fmt::Debug;

use serde::de::DeserializeOwned;

use crate::dao;
use crate::runtime::error::MagicBoxError;
use crate::runtime::response::Code;
use crate::runtime::result::MagicBoxResult;

/// 获取配置项并转为指定类型
pub(crate) fn get_setting<T: DeserializeOwned + Debug>(name: &str) -> Option<T> {
    let value = get_setting_value(name)?;

    // 解析JSON为结构
    let result = serde_json::from_str::<T>(value.as_str());
    if result.is_err() {
        log::error!("解析配置失败: {}", result.unwrap_err().to_string());

        return None;
    }

    Some(result.unwrap())
}

/// 获取配置项值
pub(crate) fn get_setting_value(name: &str) -> Option<String> {
    let connection = dao::connection::main();

    // 查询数据
    let result = connection.prepare("select value from settings where name = ?1 limit 1").unwrap().query_row(&[&name], |row| {
        Ok(row.get::<_, String>(0)?)
    });

    if result.is_err() {
        log::error!("查询配置失败: {}", result.unwrap_err().to_string());

        return None;
    }

    Some(result.unwrap())
}

/// 设置配置项值
pub(crate) fn set_setting(name: &str, value: &str) -> MagicBoxResult<()> {
    let connection = dao::connection::main();

    let result = get_setting_value(name);
    if result.is_some() {
        let result = connection.execute("update settings set value =?1 where name =?2", (value, name));
        if result.is_err() {
            log::error!("更新配置失败: {}", result.unwrap_err().to_string());

            return Err(MagicBoxError::new(Code::UndefinedError, "数据库错误"));
        }
    } else {
        let result = connection.execute("insert into settings (name, value) values (?1, ?2)", (name, value));
        if result.is_err() {
            log::error!("插入配置失败: {}", result.unwrap_err().to_string());

            return Err(MagicBoxError::new(Code::UndefinedError, "数据库错误"));
        }
    }

    Ok(())
}